package com.boot.main.utils;

import com.boot.main.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
@Slf4j
public class SerializableUtil {
    private SerializableUtil(){}
    public static byte[] serializable(Object object){
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try{
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        }catch (IOException e){
            log.error("SerializableUtil工具类序列化出现IOException异常:" + e.getMessage());
        }finally {
            try{
                if(oos!=null){
                    oos.close();
                }
                if(baos!=null){
                    baos.close();
                }
            }catch (IOException e){
                log.error("SerializableUtil工具类反序列化出现IOException异常：{}", e.getMessage());
                 throw new CustomException(601, "SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
            }
            return baos.toByteArray();
        }
    }

    public static Object unserializable(byte[] bytes){
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;
        try{
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return  ois.readObject();
        }catch (ClassNotFoundException e){
            log.error("SerializableUtil工具类反序列化出现ClassNotFoundException异常:{}", e.getMessage());
        }catch (IOException e){
            log.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
            throw new CustomException(602, "SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
        } finally {
            try{
                if(ois != null){
                    ois.close();
                }
                if(bais != null){
                    bais.close();
                }
            } catch (IOException e){
                log.error("SerializableUtil工具类反序列化出现IOException异常:{}", e.getMessage());
                throw new CustomException(603, "SerializableUtil工具类反序列化出现IOException异常:" + e.getMessage());
            }
            return null;
        }
    }
}
